//
//  SetPaymentPasswordController.swift
//  mggz
//
//  Created by ShareAnimation on 2017/9/14.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import SwiftProgressHUD
class SetPaymentPasswordController: UIViewController {
    var securityAlert:TWLAlertView?
    fileprivate var securityView:PayResetPopViw?
    
//    private var headPanel: UIView = {
//        let view = UIView()
//        view.backgroundColor = UIColor.white
//        return view
//    }()
    
    //请输入手机号
    private var phoneInputTitleLabel: UILabel = {
        let label = UILabel()
        label.font = wwFont_Regular(15)
        label.textColor = UIColor.mg_lightGray
        return label
    }()
    
    private var verificationCodeTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "请输入短信验证码"
        textField.font = wwFont_Regular(17)
        let leftView = UIView(frame: CGRect.init(x: 0, y: 0, width: 25, height: 25))
        let imageView = UIImageView(frame: CGRect.init(x: 0, y: 0, width: 20, height: 20))
        imageView.image = UIImage(named: "reply_n")
        imageView.contentMode = .scaleAspectFit
        leftView.addSubview(imageView)
        imageView.center = CGPoint(x: 25/2, y: 25/2)
        
        textField.leftView = leftView
        textField.leftViewMode = .always
        
        return textField
    }()
    
    var countDownButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: #selector(doCountDownAction(_:)), for: .touchUpInside)
        button.layer.cornerRadius = 6
        button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        button.setTitle("获取验证码", for: .normal)
        button.backgroundColor = colorWithRGB(r:16, g: 142, b: 233)
        
        return button
    }()
    
    
    /***密码区域***/
    private var passwordPanel: UIView = {
        let view = UIView()
        view.isUserInteractionEnabled = true
        view.backgroundColor = UIColor.white
        return view
    }()
    
    private let passwordInputFirstView = PasswordInputView()
    
    private var firstInputPassWordTitleLabel: UILabel = {
        let label = UILabel()
        label.text = "请输入交易密码"
        label.font = wwFont_Regular(15)
        return label
    }()
    
    private let passwordInputSecondView = PasswordInputView()
    
    private var secondInputPassWordTitleLabel: UILabel = {
        let label = UILabel()
        label.text = "请再次输入交易密码"
        label.font = wwFont_Regular(15)
        return label
    }()
    
    private var submitButton:UIButton = {
        let button = UIButton()
        button.backgroundColor = UIColor.mg_blue
        button.setTitle("提交", for: .normal)
        button.layer.cornerRadius = 8
        button.layer.shadowColor = UIColor.black.cgColor
        button.layer.shadowOffset = CGSize(width: 1, height: 1)
        button.layer.shadowOpacity = 0.2
        return button
    }()
    
    private var firstPassword: String?
    private var secondPassword: String?
    
    private var userInfoModel: UserInfoModel?
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        WWProgressHUD.dismiss()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "设置交易密码"
        self.view.backgroundColor = UIColor.mg_backgroundGray
        
//        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
//        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
        
        self.setupViews()
        self.getData()
        
        self.passwordInputFirstView.isUserInteractionEnabled = true
        self.passwordInputSecondView.isUserInteractionEnabled = true
        self.passwordInputFirstView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(doPasswordFirstViewTap)))
        self.passwordInputSecondView.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(doPasswordSecondViewTap)))
        self.passwordInputFirstView.passwordInputHandler = {[unowned self](password) in
            if password.characters.count == 6 {
             self.passwordInputSecondView.setFirstResponder = true
            }
            else {
                self.passwordInputSecondView.clear()//passwordInputFirstView正在输入的时候，会清空passwordInputSecondView
            }
            self.firstPassword = password
        }
        
        self.submitButton.addTarget(self, action: #selector(setupSecurityView), for: .touchUpInside)
        
        self.passwordInputSecondView.passwordInputHandler = {[unowned self](password) in
            if password.characters.count == 0 {
                self.passwordInputFirstView.setFirstResponder = true
            }
            self.secondPassword = password
        }
    }
    
    func setupViews() {
        /***headView***/
//        self.view.addSubview(self.headPanel)
//        self.headPanel.snp.makeConstraints { (make) in
//            make.left.right.equalTo(self.view)
//            make.top.equalTo(self.view).offset(64)
//            make.height.equalTo(80)
//        }
        
//        self.headPanel.addSubview(self.phoneInputTitleLabel)
//        self.phoneInputTitleLabel.snp.makeConstraints { (make) in//区域高度：20
//            make.top.equalTo(self.headPanel).offset(10)
//            make.right.equalTo(self.headPanel)
//            make.left.equalTo(self.headPanel).offset(20)
//            make.height.equalTo(20)
//        }
        
//        self.headPanel.addSubview(self.verificationCodeTextField)
//        self.verificationCodeTextField.snp.makeConstraints { (make) in//区域高度：40
//            make.left.equalTo(self.headPanel).offset(15)
//            make.top.equalTo(self.phoneInputTitleLabel.snp.bottom).offset(10)
//            make.height.equalTo(30)
//        }
        
//        self.headPanel.addSubview(self.countDownButton)
//        self.countDownButton.snp.makeConstraints { (make) in
//            make.left.equalTo(self.verificationCodeTextField.snp.right)
//            make.right.equalTo(self.headPanel).offset(-15)
//            make.centerY.equalTo(self.verificationCodeTextField)
//            make.height.equalTo(30)
//            make.width.equalTo(80)
//        }
        
        /***密码区域***/
        self.view.addSubview(self.passwordPanel)
        self.passwordPanel.snp.makeConstraints { (make) in
            make.top.equalTo(self.view).offset(64)
            make.left.right.equalTo(self.view)
            make.height.equalTo(230)
        }
        
    self.passwordPanel.addSubview(self.firstInputPassWordTitleLabel)
        self.firstInputPassWordTitleLabel.snp.makeConstraints { (make) in//高度：40
            make.centerX.equalTo(self.passwordPanel)
            make.top.equalTo(self.passwordPanel).offset(10)
            make.height.equalTo(30)
        }
        
        self.passwordPanel.addSubview(passwordInputFirstView)
        self.passwordInputFirstView.snp.makeConstraints { (make) in
            make.top.equalTo(self.firstInputPassWordTitleLabel.snp.bottom).offset(10)//高度：70
            make.centerX.equalTo(self.passwordPanel)
            make.width.equalTo(300)
            make.height.equalTo(60)
        }
        
        self.passwordPanel.addSubview(self.secondInputPassWordTitleLabel)
        self.secondInputPassWordTitleLabel.snp.makeConstraints { (make) in//高度40
            make.centerX.equalTo(self.passwordPanel)
            make.top.equalTo(self.passwordInputFirstView.snp.bottom).offset(10)
            make.height.equalTo(30)
        }
        
        self.passwordPanel.addSubview(self.passwordInputSecondView)
        self.passwordInputSecondView.snp.makeConstraints { (make) in//高度：70
            make.width.equalTo(300)
            make.height.equalTo(60)
            make.top.equalTo(self.secondInputPassWordTitleLabel.snp.bottom).offset(10)
            make.centerX.equalTo(self.passwordPanel)
        }
        
        /***提交按钮***/
        self.view.addSubview(self.submitButton)
        self.submitButton.snp.makeConstraints { (make) in
            make.centerX.equalTo(self.view)
            make.top.equalTo(self.passwordPanel.snp.bottom).offset(40)
            make.width.equalTo(220)
            make.height.equalTo(40)
        }
    }
    
    @objc fileprivate func setupSecurityView(){
    self.passwordInputSecondView.textField.resignFirstResponder()
        guard self.firstPassword != nil && self.firstPassword!.characters.count != 0 else {
            WWError("请输入密码")
            return
        }
        guard self.secondPassword != nil && self.secondPassword!.characters.count != 0 else {
            WWError("请输入确认密码")
            return
        }
        guard self.firstPassword == self.secondPassword else {
            WWError("两次密码不同")
            return
        }
        
        self.securityAlert = TWLAlertView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
        let securityView = PayResetPopViw.init(frame: CGRect(x: 0, y: 0, width: 271, height: 180))
        securityView.cancel.addTarget(self, action: #selector(alertCancelButton), for: .touchUpInside)
        securityView.phoneNum.text = self.userInfoModel?.cellPoneNumber
        securityView.securityButton.addTarget(self, action: #selector(doCountDownAction(_:)), for: .touchUpInside)
        securityView.sureButton.addTarget(self, action: #selector(doSubmitAction), for: .touchUpInside)
        self.securityView = securityView
        self.securityAlert?.initWithCustomView(securityView, frame: CGRect(x: 0, y: 0, width: 271, height: 180))
        let keyWindow = UIApplication.shared.keyWindow
        keyWindow?.addSubview(self.securityAlert!)
    }
    @objc fileprivate func alertCancelButton(){
        self.securityAlert?.cancleView()
    }
    @objc func doCountDownAction(_ button: UIButton) {
        
        guard  let model = self.userInfoModel, let phoneNumber = model.cellPoneNumber else {
            SwiftProgressHUD.showOnlyText("只有通过认证的用户才能设置交易密码")
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.5, execute: {
                SwiftProgressHUD.hideAllHUD()
            })
            return
        }
        
        button.startWithTime(60, title: "获取验证码", countDownTitle: "重新发送", mainColor: button.backgroundColor!, countColor: UIColor.gray)
        
        UserModel.requestSecurityCode(phoneNumber: phoneNumber, flag: FlagType.agentapply) { (response) in
            if response.success {
            #if DEBUG
                WWInform(response.value ?? "好像是空的")
            #else
            #endif
            }
            else
            {
                WWError(response.message)
            }
        }
    }
    
    @objc func doPasswordFirstViewTap() {
        self.passwordInputFirstView.setFirstResponder = true
    }
    
    @objc func doPasswordSecondViewTap() {
        self.passwordInputSecondView.setFirstResponder = true
    }
    
    @objc func doSubmitAction() {
        
        guard let model = self.userInfoModel, let phoneNumber = model.cellPoneNumber else {
            SwiftProgressHUD.showOnlyText("只有通过认证的用户才能设置交易密码")
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.5, execute: {
                SwiftProgressHUD.hideAllHUD()
            })
            return
        }
        guard let verificationString = self.securityView?.securityTextField.text else {
            WWError("验证码没有输入")
            return
        }

        WWBeginLoadingWithStatus("开始设置")
        PaymentPassword.setupPaymentPassword(phoneNumber, verifycode: verificationString, payPassword: self.firstPassword!) { (response) in
            if response.success {
                WWSuccess("设置成功")
                self.securityAlert?.cancleView()
            self.navigationController?.popViewController(animated: true)
            }
            else {
                if response.message.contains("验证码输入错误"){
                    
                }
                WWError(response.message)
                
            }
        }
    }
    
    func getData() {
        WWBeginLoadingWithStatus("加载用户数据..")
        UserInfoModel.getMigrantWorkInfo { (response) in
            if response.success {
                self.userInfoModel = response.value
                
                guard response.value != nil  else{
                    return
                }
                self.phoneInputTitleLabel.text = "请输入手机号：\(response.value!.cellPoneNumber ?? "")收到的短信验证码"
            }
            else {
                WWError("获取用户信息出错")
            }
            WWEndLoading()
        }
    }
    
    func keyboardWillShow(_ notification: Notification) {
        let userInfo = notification.userInfo as! [String: Any]
        let aValue = userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue
        var keyboardRect = aValue.cgRectValue
        keyboardRect = self.view.convert(keyboardRect, from: nil)
        
        let keyboardTop = keyboardRect.origin.y
        let rect = self.passwordPanel.superview?.convert(self.passwordPanel.frame, to: self.view)
        let coordinate = rect!.origin.y + rect!.size.height - keyboardTop
        let animationDurationValue = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSValue
        var animationDuration: TimeInterval?
        animationDurationValue.getValue(&animationDuration)
        UIView.animate(withDuration: animationDuration ?? 0.25) {
            if coordinate > 0 {
                self.view.transform = CGAffineTransform.init(translationX: 0, y: -coordinate-60)
            }
        }
    }
    
    func keyboardWillHide(_ notification: Notification) {
        let userInfo = notification.userInfo as! [String: Any]
        let animationDurationValue = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSValue
        var animationDuration: TimeInterval?
        animationDurationValue.getValue(&animationDuration)
        UIView.animate(withDuration: animationDuration ?? 0.25) { 
            self.view.transform = CGAffineTransform.identity
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}
